<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>下拉菜单</title>
<style>
.dropdown {
  position: relative;
  display: inline-block;
}

.dropbtn {
  background-color: #4CAF50;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
  display: block;
}

.dropdown:hover .dropbtn {
  background-color: #3e8e41;
}

</style>
</head>
<body>

<div class="dropdown">
  <button class="dropbtn">下拉菜单</button>
  <div class="dropdown-content" id="dropdown">
    <a href="#">链接 1</a>
    <a href="#">链接 2</a>
    <a href="#">链接 3</a>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const dropdown = document.getElementById('dropdown');
  const dropbtn = document.querySelector('.dropbtn');

  // 点击下拉按钮时显示下拉菜单
  dropbtn.addEventListener('click', function(event) {
    dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
    event.stopPropagation(); // 阻止事件冒泡
  });

  // 点击下拉菜单外的区域时隐藏下拉菜单
  document.addEventListener('click', function() {
    dropdown.style.display = 'none';
  });

  // 点击下拉菜单项时阻止事件冒泡
  dropdown.addEventListener('click', function(event) {
    event.stopPropagation();
  });
});

</script>
</body>
</html>
